import * as qiniu from './qiniu.js'
import { post_md5 } from '../../common/request'
import { Base64 } from '../../js_sdk/js-base64.js'
import { pathToBase64, base64ToPath } from '../../js_sdk/gsq-image-tools/image-tools/index.js'

class Uploader {
  constructor() { }

  uploadImage() {
    let _this = this

    return new Promise((resolve, reject) => {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        async success(res) {
          let file = await _this.filePathToBase64(res.tempFilePaths[0])
          if (file.length > 4194304) {
            reject('图片大小不能超过4M')
            uni.showToast({
              title: '图片大小不能超过4M',
              icon: 'none'
            })
          }
          else {
            uni.showLoading({ mask: true, title: '上传中...' })
            let result = await _this.qiniuUpload(file)
            uni.hideLoading({ mask: true, title: '上传中...' })
            resolve(result)
          }
        }
      })
    })
  }

  async filePathToBase64(filePath) {

    let file = await pathToBase64(filePath)
    var index = file.indexOf('base64,')
    file = file.substring(index + 'base64,'.length)
    return file
  }

  async qiniuUpload(file) {
    let res = await post_md5('/sys/oss/imguptoken')
    let token = res.data.token
    let domain = res.data.domain
    var result = await this.doUpload(file, token)
    var url = domain + '/' + result.key
    return url
  }

  doUpload(file, token) {
    let fileName = this.generateFileName()
    return new Promise((resolve, reject) => {
      uni.request({
        url: 'http://up-z1.qiniup.com/putb64/-1/key/' + Base64.encode(fileName),
        method: 'POST',
        header: {
          'Authorization': 'UpToken ' + token,
          'Content-Type': 'application/octet-stream'
        },
        data: file,
        success: function (res) {
          resolve(res.data)
        },
        fail: function (err) {
          reject(err)
        }
      })
    })
  }

  generateFileName() {
    let randomNum = Math.floor(Math.random() * 10000)
    let timespan = Date.parse(new Date())
    return timespan.toString() + randomNum.toString()
  }
}

const uploader = new Uploader()
export default uploader
